<?php

namespace backend\controllers;

use backend\actions\DeleteAction;
use backend\actions\SortAction;
use backend\models\Article;
use Yii;
use Exception;
use backend\models\Category;
use backend\models\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CategoryController implements the CRUD actions for Category model.
 */
class CategoryController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class'   => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'upload' => [
                'class'  => 'backend\widgets\ueditor\UEditorAction',
                'config' => [
                    "imageRoot"            => Yii::getAlias('@pathRoot'),
                    "fileRoot"             => Yii::getAlias('@pathRoot'),
                    "imagePathFormat"      => "/uploads/image/{yyyy}{mm}{dd}/{time}{rand:6}", //上传保存路径
                    "imageManagerListPath" => '/uploads/image/',
                    "UrlRoot"              => '',
                ],
            ],
            'delete' => [
                'class'      => DeleteAction::className(),
                'modelClass' => Category::className(),
            ],
            'sort'   => [
                'class'      => SortAction::className(),
                'modelClass' => Category::className(),
            ],
        ];
    }


    /**
     * Lists all Category models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel  = new CategorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render(
            'index',
            [
                'searchModel'  => $searchModel,
                'dataProvider' => $dataProvider,
            ]
        );
    }

    /**
     * Displays a single Category model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render(
            'view',
            [
                'model' => $this->findModel($id),
            ]
        );
    }

    /**
     * Finds the Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Category::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }


    /**
     * @Notes Creates a new Category model. If creation is successful, the browser will be redirected to the 'view' page.
     * @Interface actionCreate
     *
     * @return string|\yii\web\Response
     * @throws Exception
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2020-01-07 2:36
     */
    public function actionCreate()
    {
        $model = new Category();
        if (Yii::$app->request->isPost) {
            if (!$model->load(Yii::$app->request->post())) {
                throw new Exception($model->getErrors());
            }
            if (empty($model->parent_id)) {
                $model->makeRoot();
            } else {
                $_parentModel = Category::findOne(['id' => $model->parent_id]);
                $model->appendTo($_parentModel);
            }

            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render(
            'create',
            [
                'model' => $model,
            ]
        );
    }

    /**
     * Updates an existing Category model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost) {
            if (!$model->load(Yii::$app->request->post())) {
                throw new Exception($model->getErrors());
            }
            if (!$model->isRoot()) {
                if (empty($model->parent_id)) {
                    $model->makeRoot();
                } else {
                    $_parentModel = Category::findOne(['id' => $model->parent_id]);
                    $model->appendTo($_parentModel);
                }
            }
            if ($model->save()) {
                if (yii::$app->getRequest()->getIsAjax()) {
                    return json_encode(['message' => '设置成功！']);
                } else {
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }
        }

        return $this->render(
            'update',
            [
                'model' => $model,
            ]
        );
    }


}
